#include <Wire.h>
#include "Adafruit_SGP30.h"
#include <WiFi.h>

#define SCL 22
#define SDA 21
#define ohumiPin 32
#define pumpPin 2
const char *ssid = "Nice";
const char *password = "12312312";
WiFiClient client;
const IPAddress serverIP(192, 168, 108, 129);  //欲访问的地址
uint16_t serverPort = 5552;                    //服务器端口号

Adafruit_SGP30 sgp;

float c_min = 4095.0;
float c_max = 2600.0;
float m_min = 0.0;
float m_max = 100.0;
int speed = 400;  //0-1000
char sendBuf[50] = { 0 }, ohumiBuf[10] = { 0 }, co2Buf[10] = { 0 };
int ohumi, count = 0;
void TVOC_CO2();
void Ohumi();
void Mortor_Init();
void Load();

void setup() {
  Serial.begin(115200);
  Wire.begin(SDA, SCL);
  analogReadResolution(12);
  pinMode(pumpPin,OUTPUT);
  digitalWrite(pumpPin,HIGH);
  if (!sgp.begin()) {
    while (1)
      ;
  }
  WiFi.mode(WIFI_STA);
  WiFi.setSleep(false);  //关闭STA模式下wifi休眠，提高响应速度
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
}

void loop() {
  if (client.connect(serverIP, serverPort))  //尝试访问目标地址
  {
    Serial.println("connect ok");

    while (client.connected() || client.available()) {
      TVOC_CO2();
      Ohumi();

      memset(sendBuf, 0, sizeof(sendBuf));
      
      strcpy(sendBuf, "B");
      strcat(sendBuf, ohumiBuf);
      strcat(sendBuf, "-");
      strcat(sendBuf, co2Buf);


      client.print(sendBuf);
      if (client.available())  //如果有数据可读取
      {
        String line = client.readStringUntil('\n');  //读取数据到换行符
        if(line.indexOf("ON") != -1) {
          digitalWrite(pumpPin,LOW);
        }
        if(line.indexOf("OFF") != -1) {
          digitalWrite(pumpPin,HIGH);
        }
        Serial.println(line);
      }
      delay(2000);
    }

    Serial.println("关闭当前连接");
    client.stop();  //关闭客户端
  } else {
    Serial.println("connect fail");
    client.stop();  //关闭客户端
  }
}

void TVOC_CO2() {
  if (!sgp.IAQmeasure()) {
    Serial.println("Measurement failed");
    return;
  }
  sprintf(co2Buf, "%d", sgp.eCO2);
}
void Ohumi() {
  int c_cur = analogRead(32);
  ohumi = (c_cur - c_min) * 50.0 / (c_max - c_min) + 50;
  sprintf(ohumiBuf, "%d", ohumi);
}